package com.example.planetexploder.utils.screenshot;

import android.annotation.SuppressLint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

/**
 * 触摸监听器
 * @author 宋熙然
 * 修改日期：2019.10.24
 */
public class MyOnTouchListener implements View.OnTouchListener {

    private static final String TAG = "MyOnTouchListener";

    private ImageView iv;
    private ImageView iv_v;
    private ImageView iv_h;
    private int y;
    private int x;

    public int getY() {
        return y;
    }

    public int getX() {
        return x;
    }

    private int max_up;
    private int max_down;
    private int max_left;
    private int max_right;

    public MyOnTouchListener(ImageView iv, ImageView iv_v, ImageView iv_h, int max_up, int max_down, int max_left, int max_right) {
        this.iv = iv;
        this.iv_v = iv_v;
        this.iv_h = iv_h;
        this.max_up = max_up;
        this.max_down = max_down;
        this.max_left = max_left;
        this.max_right = max_right;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, "onTouch: 按下");
                //获取当前按下的坐标
                x = (int) event.getRawX();
                y = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                //获取移动后的坐标
                int moveX = (int) event.getRawX();
                int moveY = (int) event.getRawY();
                //拿到手指移动距离的大小
                int move_bigX = moveX - x;
                int move_bigY = moveY - y;
                Log.d(TAG, "X:" + x + "  Y:" + y);
                //拿到当前控件未移动的坐标
                int left = iv.getLeft();
                int top = iv.getTop();
                left += move_bigX;
                top += move_bigY;

                if(left<max_left) left = max_left;
                if(left>max_right) left = max_right;
                if(top<max_up) top = max_up;
                if(top>max_down) top = max_down;

                int right = left + iv.getWidth();
                int bottom = top + iv.getHeight();
                iv.layout(left, top, right, bottom);

                iv_v.layout(iv_v.getLeft(), top, iv_v.getLeft() + iv_v.getWidth(), top + iv_v.getHeight());
                iv_h.layout(left, iv_h.getTop(), left + iv_h.getWidth(), iv_h.getTop() + iv_h.getHeight());

                x = moveX;
                y = moveY;
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, "onTouch: 抬起");
                break;
        }
        return true;//此处一定要返回true，否则监听不生效
    }
}
